<template>
  <div class="login-register-form">
    <el-form :model="subForm" status-icon :rules="rules" ref="subForm" label-width="100px" class="demo-ruleForm">

      <el-form-item label="职位" prop="post">
        <el-select v-model="subForm.post" placeholder="请选择职位">
          <el-option label="学生" value="student"></el-option>
          <el-option label="教师" value="teacher"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="工号/学号" prop="workId">
        <el-input
          type="text"
          v-model="subForm.workId"
          autocomplete="off"
          clearable
        />
      </el-form-item>

      <el-form-item label="密码" prop="pass">
        <el-input
        type="password"
        v-model="subForm.pass"
        autocomplete="off"
        clearable
        show-password
      />
      </el-form-item>

      <el-form-item>
        <el-button
          type="success" plain 
          @click="submitForm('subForm')"
          :loading=loading
        >登录</el-button>
      </el-form-item>

    </el-form>
  </div>
</template>

<script>
import request from '@/utils/requestMethod';
import apis from '@/utils/api';
import { Message } from 'element-ui';

export default {
  data() {
    /**
     *  对用户名进行校验
     */
    const validateUsername = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入工号或学号'));
      } else {
        callback()
      }
    };

    /**
     *  对密码进行校验
     */
    const validatePassword = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'));
      } else {
        callback()
      }
    };

    /**
     *  对职位进行校验
     */
    const validatePost = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请选择职位'));
      } else {
        callback()
      }
    };

    return {
      subForm: {
        workId: '',
        pass: '',
        post: ''
      },
      loading: false,
      rules: {
        workId: [
          { validator: validateUsername, trigger: 'blur' }
        ],
        pass: [
          { validator: validatePassword, trigger: 'blur' }
        ],
        post: [
          { validator: validatePost, trigger: 'blur' }
        ]
      }
    };
  },
  methods: {
    /**
     *  处理登录请求
     */
    submitForm(formName) {
      this.loading = true;
      this.$refs[formName].validate((valid) => {
        if (valid) {
          const {
            workId,
            pass,
            post
          } = this.subForm;

          // 开发阶段为了不和后端联调而临时加入的登录代码
          // const userInfo = {
          //   workId,
          //   post,
          //   password: pass,
          //   username: 'martin_user',
          //   name: 'martin',
          //   college: '计算机',
          //   role: 0
          // }

          // localStorage.setItem('userInfo', JSON.stringify(userInfo));
          // this.$router.push('/layout');

          // 发送登录请求
          const loginData = {
            workId,
            password: pass,
            post
          }

          request(apis.login_url, {
            method: 'POST',
            body: loginData
          }).then(res => {
            const {
              token,
              objects,
              message
            } = res.data;

            if (objects.length > 0) {
              delete objects[0].password;
              localStorage.setItem('userInfo', JSON.stringify(objects[0]));
              localStorage.setItem('token', token);
              Message.success(message);
              this.$router.push('/layout');
            } else {
              Message.warning(message);
            }
          }).finally(() => {
            this.loading = false;
          })

        } else {
          console.log('error submit!!');
          this.loading = false;
          return false;
        }
      });
    }
  }
}
</script>